﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace XUtility
{
    public class StringClass
    {
        /// <summary>
        /// 截取指定长度的文本
        /// </summary>
        /// <param name="str">原字符串</param>
        /// <param name="longs">截取长度,汉字1个占2长度</param>
        /// <returns></returns>
        public static String LockLong(String str, Int32 longs)
        {
            String tmpStr = str;
            Byte[] tmpBY = System.Text.Encoding.Default.GetBytes(tmpStr);
            Int32 textlong = longs;
            if (tmpBY.Length > textlong)
            {
                Byte[] newBY = new Byte[textlong];
                for (Int32 i = 0; i < textlong; i++)
                    newBY[i] = tmpBY[i];
                tmpBY = newBY;
                tmpStr = System.Text.Encoding.Default.GetString(tmpBY) + "...";
            }

            return tmpStr;
        }

        /// <summary>
        /// 生成随机字符串，不会包含特殊符号
        /// </summary>
        /// <param name="leng">字符串长度，默认43，符合微信的加密密钥长度</param>
        /// <returns></returns>
        public static String GetRandomStr(Int32 leng = 43)
        {
            var arrChar = new char[]{
           'a','b','d','c','e','f','g','h','i','j','k','l','m','n','p','r','q','s','t','u','v','w','z','y','x',
           '0','1','2','3','4','5','6','7','8','9',
           'A','B','C','D','E','F','G','H','I','J','K','L','M','N','Q','P','R','T','S','V','U','W','X','Y','Z'
          };

            var num = new StringBuilder();

            Random rnd = new Random(DateTime.Now.Millisecond);
            for (int i = 0; i < leng; i++)
            {
                num.Append(arrChar[rnd.Next(0, arrChar.Length)].ToString());

            }

            return num.ToString();
        }
    }
}
